import Cookies from 'js-cookie'
import Fingerprint2 from 'fingerprintjs2'

const state = {
  sidebar: {
    opened: Cookies.get('sidebarStatus') ? !!+Cookies.get('sidebarStatus') : true,
    withoutAnimation: false
  },
  device: 'desktop',
  deviceId: ''
}

const mutations = {
  TOGGLE_SIDEBAR: state => {
    state.sidebar.opened = !state.sidebar.opened
    state.sidebar.withoutAnimation = false
    if (state.sidebar.opened) {
      Cookies.set('sidebarStatus', 1)
    } else {
      Cookies.set('sidebarStatus', 0)
    }
  },
  CLOSE_SIDEBAR: (state, withoutAnimation) => {
    Cookies.set('sidebarStatus', 0)
    state.sidebar.opened = false
    state.sidebar.withoutAnimation = withoutAnimation
  },
  TOGGLE_DEVICE: (state, device) => {
    state.device = device
  },
  TOGGLE_DEVICEDID: (state, deviceId) => {
    state.deviceId = deviceId
  }
}

const actions = {
  toggleSideBar({ commit }) {
    commit('TOGGLE_SIDEBAR')
  },
  closeSideBar({ commit }, { withoutAnimation }) {
    commit('CLOSE_SIDEBAR', withoutAnimation)
  },
  toggleDevice({ commit }, device) {
    commit('TOGGLE_DEVICE', device)
  },
  toggleDeviceId({ commit }, deviceId) {
    commit('TOGGLE_DEVICEDID', deviceId)
  },
  getDeviceId({ commit, state }) {
    return new Promise((resolve, reject) => {
      Fingerprint2.get(function(components) {
        const values = components.map(function(component, index) {
          if (index === 0) { // 把微信浏览器里UA的wifi或4G等网络替换成空,不然切换网络会ID不一样
            return component.value.replace(/\bNetType\/\w+\b/, '')
          }
          return component.value
        })
        // 生成最终id murmur
        const deviceId = Fingerprint2.x64hash128(values.join(''), 31)
        commit('TOGGLE_DEVICEDID', deviceId)
        // console.log('浏览器指纹码：' + deviceId)
        return resolve(deviceId)
      })
    })
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
